package com.banciyuan.bcywebview.biz.goods.shoppingcart;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.goods.order.confirmorder.ConfirmOrderActivity;
import com.banciyuan.bcywebview.biz.goods.store.AllGoodsActivity;
import com.banciyuan.bcywebview.utils.currency.CurrencyUtil;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.BaseGoods;
import de.greenrobot.daoexample.model.DetailGoods;

public class ShoppingCartActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView mRecyclerView;
    private View shoppingEmptyView;
    private ImageView ivSelectAll;
    private ShoppingCartAdapter shoppingCartAdapter;
    private boolean selectAll = true;
    private List<DetailGoods> mCartGoodsList;
    private TextView tvItemCount;
    private TextView tvTotalPrice;
    private TextView go_discover_acg;
    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoppingcart_layout);
        initArgs();
        initActionbar();
        initUi();
        initAction();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initActionbar() {
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, findViewById(R.id.base_action_bar));
        mActionbarHelper.setTitle(getString(R.string.shopping_cart));
    }

    @Override
    protected void initUi() {
        mRecyclerView = (RecyclerView) findViewById(R.id.shoppingcart_rv);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerView.ItemAnimator animator = mRecyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        shoppingEmptyView = findViewById(R.id.shoppingcart_emptyview);
        ivSelectAll = (ImageView) findViewById(R.id.iv_select_all);
        tvItemCount = (TextView) findViewById(R.id.tv_go_order);
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        go_discover_acg = (TextView) findViewById(R.id.tv_go_order_acg);
        ((ImageView)findViewById(R.id.iv_empty_pic)).setImageResource(R.drawable.ic_empty_cart);
    }

    @Override
    protected void initAction() {
        ivSelectAll.setOnClickListener(this);
        tvItemCount.setOnClickListener(this);
        go_discover_acg.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        try {
            getData();
            setTotalCountAndPrice();
            isShoppingCartEmpty();
            shoppingCartAdapter = new ShoppingCartAdapter(this, mCartGoodsList);
            mRecyclerView.setAdapter(shoppingCartAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void isShoppingCartEmpty() {
        if (mCartGoodsList.isEmpty()) {
            shoppingEmptyView.setVisibility(View.VISIBLE);
        } else {
            shoppingEmptyView.setVisibility(View.GONE);
        }
    }

    private void getData() {
        mCartGoodsList = ShoppingCartHelper.getShoppingItems(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_select_all:
                dealSelect();
                break;
            case R.id.tv_go_order:
                tvItemCount.setClickable(false);
                gotoOrder();
                break;
            case R.id.tv_go_order_acg:
                gotoUtil.gotoAct(this, AllGoodsActivity.class);
                break;
        }
    }

    private void dealSelect() {
        ivSelectAll.setImageResource(selectAll ? R.drawable.ic_checkbox_normal : R.drawable.ic_checkbox_pressed);
        selectAll = !selectAll;
        for (int i = 0; i < mCartGoodsList.size(); i++) {
            mCartGoodsList.get(i).setIs_select(selectAll);
        }
        shoppingCartAdapter.notifyDataSetChanged();
        setTotalCountAndPrice();
    }

    private void gotoOrder() {
        List<BaseGoods> selectDetailGoods = new ArrayList<>();
        for (int i = 0; i < mCartGoodsList.size(); i++) {
            DetailGoods detailGoods = mCartGoodsList.get(i);
            if (detailGoods.is_select())
                selectDetailGoods.add(new BaseGoods(detailGoods.getZg_id(), detailGoods.getSelect_sku().getZps_id(), detailGoods.getCount()));
        }
        if (!selectDetailGoods.isEmpty()) {
            getPreOrder(selectDetailGoods);
        } else {
            MyToast.show(this, getString(R.string.not_choose_goods));
            tvItemCount.setClickable(true);
        }
    }

    private void getPreOrder(List<BaseGoods> selectDetailGoods) {
        String url = HttpUtils.BASE_URL + ZhipinApi.getPreCreateOrder();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, new Gson().toJson(selectDetailGoods)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, ShoppingCartActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                        String cartId = jsonObject.getString("pre");
                        List<DetailGoods> delGoods = new Gson().fromJson(jsonObject.getString("del"), new TypeToken<List<DetailGoods>>() {
                        }.getType());
                        processPreOderResult(cartId, delGoods);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tvItemCount.setClickable(true);
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                tvItemCount.setClickable(true);
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private void processPreOderResult(String cartId, List<DetailGoods> delGoods) {
        if (null != delGoods && !delGoods.isEmpty())
            deleteInvalidGoods(delGoods);
        if (!TextUtils.isEmpty(cartId))
            gotoConfirmOrder(cartId);
        else
            refreshSelf();
    }

    private void refreshSelf() {
        MyToast.show(this, getString(R.string.allgoods_invalid));
        initData();
    }

    private void deleteInvalidGoods(List<DetailGoods> delGoods) {
        ShoppingCartHelper.deleteMutilSimpleGoodsItem(this, delGoods);
    }

    private void gotoConfirmOrder(String cartId) {
        Intent intent = new Intent(ShoppingCartActivity.this, ConfirmOrderActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, cartId);
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, ConfirmOrderActivity.SHOPPINGCART_TYPE);
        startActivityForResult(intent, ConfirmOrderActivity.CONFIRMORDER);
    }

    public void setTotalCountAndPrice() {
        int totalCount = 0;
        float totalPrice = 0;
        int selectItem = 0;
        for (int i = 0; i < mCartGoodsList.size(); i++) {
            DetailGoods detailGoods = mCartGoodsList.get(i);
            if (detailGoods.is_select()) {
                selectItem++;
                totalCount += detailGoods.getCount();
                totalPrice += (Float.valueOf(detailGoods.getBasic_price()) + Float.valueOf(detailGoods.getSelect_sku().getAdd_price())) * detailGoods.getCount();
            }
        }
        tvItemCount.setText(String.format(getString(R.string.order_count_format), totalCount));
        tvTotalPrice.setText(String.format(getResources().getString(R.string.total_price_format), CurrencyUtil.getMoney(totalPrice)));
        selectAll = selectItem == mCartGoodsList.size();
        ivSelectAll.setImageResource(selectAll ? R.drawable.ic_checkbox_pressed : R.drawable.ic_checkbox_normal);
    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}
